import { observer } from 'mobx-react-lite';
import React, { useCallback } from 'react';
// import { useLocation, useMatch, useNavigate, useRoutes, useSearchParams } from 'react-router-dom';
import { useRoutes } from 'react-router-dom';
import LazyWrapper from 'Common/LazyWrapper';
// import queryString from 'query-string';
// import { host, redirectTargetKey } from 'Configs/common';
import { ModuleRouterPathName } from 'Configs/router';

import type { RootStore } from 'Core/RootStore';
import type { RouteObject } from 'react-router-dom';
import Article from 'Pages/Article';
import Home from 'Pages/Home';
import Message from 'Pages/Message';

/**
 * @param store root store instace
 */
interface Props {
    store: RootStore;
    wrapperRef: React.RefObject<HTMLDivElement>;
}

/**
 * main router
 */
const RootRouter: React.FC<Props> = props => {
    // const { store, wrapperRef } = props;
    const { store } = props;
    // const navigate = useNavigate();
    // const { pathname } = useLocation();
    // const [searchParams] = useSearchParams();
    // const isMatchRouterOfLogin = useMatch({
    //     path: ModuleRouterPathName.LOGIN,
    //     caseSensitive: true,
    //     end: false,
    // });

    const getLoginPage = useCallback(
        () => LazyWrapper(import('Pages/Login'), { store: store.authStore }),
        [store.authStore],
    );
    /**
   useEffect(() => {
        if (!store.authStore.checkToken() && !isMatchRouterOfLogin) {
            navigate(`${ModuleRouterPathName.LOGIN}?${queryString.stringify({ [redirectTargetKey]: pathname })}`);
        }

        return () => {};
    }, [isMatchRouterOfLogin, navigate, pathname, store.token, store.authStore]);

    useEffect(() => {
        if (store.authStore.checkToken() && isMatchRouterOfLogin) {
            navigate(searchParams.get(redirectTargetKey) ?? host, { replace: true });
        }

        return () => {};
    }, [isMatchRouterOfLogin, navigate, store.token, searchParams, store.authStore]);

 */

    const routes: RouteObject[] = [
        {
            path: ModuleRouterPathName.LOGIN,
            caseSensitive: true,
            children: [{ index: true, element: getLoginPage() }],
        },
        {
            path: '/home',
            element: <Home />, // 这种才属于嵌套路由
            children: [
                {
                    path: 'message',
                    element: <Message />,
                },
                {
                    path: 'article',
                    element: <Article />,
                },
            ],
        },
    ];

    return useRoutes(routes);
};

export default observer(RootRouter);
